var request = require('request');
var apiOption = {
    server:"http://localhost:3000"
};
if (process.env.NODE_ENV === 'production'){
    //apiOption.server = "http://localhost:3000";
}

var _formatDistance = function(distance){
    var unit,num;
    if (distance > 1) {
        unit = "km";
        num = parseFloat(distance).toFixed(2);
    } else {
        unit = "m";
        num = parseInt(distance * 1000);
    }
    return num + unit;
};

var _showError = function(req,res,status){
    var title, content;
    if(status === 404 ) {
        title = "404, page not found";
        content = "Oh dear. Looks like we can't find this page. Sorry.";
    } else {
        title = status + ", something's gone wrong";
        content = "Something, somewhere, has gone just a little bit wrong.";
    }
    res.status(status);
    res.render('generic-text', {
        title : title,
        content : content
    });
};

var renderHomePage = function(req,res,responseBody){
    var message;
    if(!(responseBody instanceof Array)) {
        message = "API lookup error";
        responseBody = [];
    } else {
        if(!(responseBody.length)) {
            message = "No places found nearby";
        }
    }
    res.render("locations_list",{
        title:"Loc8r - find a place to work with wifi",
        pageHeader:{
            title:'Loc8r',
            strapline:'Find places to work with wifi near you!'
        },
        sidebar:'Looking for wifi and a seat? Loc8r helps you find places ' +
        'to work when out and about. Perhaps with coffee, cake or a pint? ' +
        'Let Loc8r help you find the place you\'re looking for.',
        locations:responseBody,
        message:message
    });
};

var renderLocationInfoPage = function(req,res,locDetail){
    var noReview;
    if(!locDetail.reviews.length){
        noReview = "暂时还没有评论";
    }
    res.render("location_info",{
        title:locDetail.name,
        pageHeader:{
            title:locDetail.name
        },
        sidebar:{
            context:" is on Loc8r because it has accessible wifi and space to sit down with your laptop and get some work done.",
            callToAction:"If you've been and you like it - or if you don't - please leave a review to help other people just like you."
        },
        location:locDetail,
        noReview:noReview
    });
};

var renderReviewPage = function(req,res,location) {
    res.render("location-review-form",{
        title:"Review " + location.name + " on Loc8r",
        pageHeader:{
            title:"Review " + location.name
        },
        error:req.query.err
    });
};

var getLocationInfo = function(req,res,callback){
    var requestOption,path;
    path = "/api/locations/" + req.params.locationid;
    requestOption = {
        url:apiOption.server + path,
        method:"GET",
        json:{}
    };
    request(requestOption,function(err,response,body){
        if(response.statusCode == 200) {
            var data = body;
            data.coords = {
                lng:body.coords[0],
                lat:body.coords[1]
            };
            callback(req,res,data);
        }else {
            _showError(req,res,response.statusCode);
        }

    });
};

/* get 'home' page */
module.exports.homelist = function(req,res){
    var requestOption, path;
    path = "/api/locations";
    requestOption = {
        url:apiOption.server + path,
        method:"GET",
        json:{},
        qs: {
            lng:116.482041,
            lat:39.985993,
            maxDistance:20
        }
    };
    request(requestOption,function(err,response,body){
        var i, data;
        data = body;
        if(response.statusCode == 200 && data.length > 0) {
            for (i=0;i<data.length;i++) {
                data[i].distance = _formatDistance(data[i].distance);
            }
        }
        renderHomePage(req,res,data);
    });
};

/* get 'location info' page */
module.exports.locationInfo = function(req,res){
    getLocationInfo(req,res,function(req,res,resposeData){
        renderLocationInfoPage(req,res,resposeData);
    });

};

/* get 'add new review' page */
module.exports.addReview = function(req,res){
    getLocationInfo(req,res,function(req,res,resposeData){
        renderReviewPage(req,res,resposeData);
    });
};

module.exports.doAddReview = function(req,res){
    var postData,requestOption,path;
    path = "/api/locations/" + req.params.locationid + "/reviews";
    postData = {
        author:req.body.name,
        rating:req.body.rating,
        reviewText:req.body.review
    };
    requestOption = {
        url:apiOption.server + path,
        method:"POST",
        json:postData
    };
    if(!postData.author || !postData.rating || !postData.reviewText) {
        res.redirect("/location/" + req.params.locationid + "/review/new?err=val");
    }else {
        request(requestOption,function(err,response,body){
            if(response.statusCode === 201) {
                res.redirect("/location/"+req.params.locationid);
            }else if (response.statusCode === 400 && body.name && body.name ===
                "ValidationError" ){
                console.log(body);
                res.redirect("/location/" + req.params.locationid + "/review/new?err=val");
            }else {
                console.log(body);
                _showError(req,res,response.statusCode);
            }
        });
    }
};